#!/usr/bin/env node
console.log('加拿大')

const commander = require('commander');
const inquirer = require('inquirer')
const fs = require('fs');
const path = require('path');
const vue =require('./vue.json');
const react=require('./react.json')

///修改文件名称 ----执行cli-check fixFiles a.js b.js
commander.command('fixFiles [old] [new]').action((oldname, newname) => {
    const isHave = fs.existsSync(oldname);
    if (isHave) {
        fs.renameSync(oldname, newname)
    } else {
        const files = fs.readdirSync(__dirname);///当前目录
        const list = files.filter(item => item.includes(oldname));
        let ind = 0
        list.forEach(item => {
            ind += 1
            fs.renameSync(item, `${newname.split('.')[0]}(${ind}).${newname.split('.')[1]}`)
        })
    }
})


///删除文件夹   ---执行cli-check deleteFiles 文件夹名称
commander.command('deleteFiles [name]').action((name) => {
    const isHave = fs.existsSync(name);
    if (isHave) {
        delFiles(__dirname, name)
    } else {
        console.log('无此文件')
    }
})
function delFiles(dirname, name) {
    const url = path.join(dirname, name);
    const stat = fs.statSync(url);
    ///判断是文件还是文件夹
    if (stat.isFile()) {
        //是文件删除
        fs.unlinkSync(url)
    } else {
        ///读取文件夹目录
        const lis = fs.readdirSync(url);
        lis.forEach(item => {
            delFiles(url, item);
        })
        ////删除文件夹
        fs.rmdirSync(url)
    }
}

////创建脚手架 ---执行cli-check createdGan selfs(名称)
commander.command('createdGan [projectName]').action((name) => {
    const isHave = fs.existsSync(name)
    if (isHave) {
        console.log('文件已存在')
    } else {
        inquirer.prompt([{
            type: 'list',
            message: '请选择类型',
            name: 'type',
            choices: ['vue', 'react']
        }]).then(res=>{
            ///创建文件夹
            fs.mkdirSync(name)
            if(res.type==='vue'){
               initFiles(name,vue)
            }else{
                initFiles(name,react)
            }
        })
    }
})

function initFiles(dirname,obj){
   if(obj.dirname){
       ///文件夹
       const cretUrl=path.join(dirname,obj.dirname);
       fs.mkdirSync(cretUrl);
       if(obj.children){
           obj.children.forEach(item=>{
               initFiles(cretUrl,item)
           })
       }
   }else{
       ///文件
       fs.writeFileSync(path.join(dirname, obj.filename),'')
   }
}

commander.parse(process.argv)